//
//  MuchHttpRequestManager.m
//  much
//
//  Created by weijunjie on 2019/1/2.
//  Copyright © 2019年 iOS. All rights reserved.
//

#import "HttpRequestManager.h"
#import "AFNetworking.h"
#import "DeviceInfoManager.h"
#import "DeviceDataInfo.h"

// 超时时间
const static NSTimeInterval kTimeOutTimeInterval = 30;
static NSMutableArray *_allSessionTask;
static AFURLSessionManager *_sessionManager;
@implementation MuchHttpRequestManager

+ (void)initialize {
    _sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 nil];
    _sessionManager.responseSerializer = responseSerializer;
}

+ (void)sendHttpRequestWithAPI:(NSString *)api method:(HttpRequestMethodEnum)method arguments:(nullable id)arguments andSuccessCallback:(RequestSuccess)success andFailCallback:(RequestFailed)fail {
    switch (method) {
        case HttpRequestGet:
            [self requestContent:[self initUrl:api requestType:@"GET" body:arguments] success:success failure:fail];
            break;
            
        case HttpRequestPost: {
            [self requestContent:[self initUrl:api requestType:@"POST" body:arguments] success:success failure:fail];
        }
            break;
        case HttpRequestPut:
            [self requestContent:[self initUrl:api requestType:@"PUT" body:arguments] success:success failure:fail];
            break;
        case HttpRequestDelete:
            [self requestContent:[self initUrl:api requestType:@"DELETE" body:arguments] success:success failure:fail];
            break;
        default:
            break;
    }
}

+ (void)postWithUrl:(NSString *)url body:(NSData *)body showLoading:(BOOL)show success:(RequestSuccess)success failure:(RequestFailed)failure {
    [SVProgressHUD showWithStatus:@"数据加载中..."];
    NSMutableURLRequest * request = [self initUrl:url requestType:@"POST" body:body];
    [self requestContent:request success:success failure:failure];
}

+ (void)putWithUrl:(NSString *)url body:(NSData *)body showLoading:(BOOL)show success:(RequestSuccess)success failure:(RequestFailed)failure {
    [self requestContent:[self initUrl:url requestType:@"PUT" body:body] success:success failure:failure];
}

+ (void)deleteWithUrl:(NSString *)url body:(NSData *)body showLoading:(BOOL)show success:(RequestSuccess)success failure:(RequestFailed)failure {
    [self requestContent:[self initUrl:url requestType:@"DELETE" body:body] success:success failure:failure];
}

+ (void)getWithUrl:(NSString *)url body:(NSData *)body showLoading:(BOOL)show success:(RequestSuccess)success failure:(RequestFailed)failure {
    
    [self requestContent:[self initUrl:url requestType:@"GET" body:body] success:success failure:failure];
}


+ (NSMutableURLRequest *)initUrl:(NSString *)url requestType:(NSString *)requestType body:(id)body {
    
    NSString *api = [OutsideAPIPath stringByAppendingString:url];
    
    if ([url containsString:ProvinceListAPI] || [url containsString:CityListAPI]) {
        api = [UploadAttachmentsPath stringByAppendingString:url];
    }
    
    NSString * encodedString =[api stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:requestType URLString:encodedString parameters:body error:nil];
    request.timeoutInterval = kTimeOutTimeInterval;
    NSMutableDictionary * header = [[NSMutableDictionary alloc] init];
    
//    if ([url containsString:StoreShareGetWxacodeAPI] || [url containsString:StoreShareGetWximageAPI]) {
//        [header setObject:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];
//    } else {
        [header setObject:@"application/json;charset=UTF-8" forKey:@"Content-Type"];
//    }
    if (USER.userBaseInfo.token.hasValue) {
        [header setObject:USER.userBaseInfo.token forKey:@"token"];
    }
    NSString * psid = [DeviceInfoManager idfv];
    if (psid.hasValue) [header setObject:psid forKey:@"deviceId"];
    [header setObject:kChannelValue forKey:@"channel"];
    [header setObject:@"Extended" forKey:@"lifecycle"];
    [header setObject:APP.applicationVersion forKey:@"app-ver"];
    [header setObject:@"IOS" forKey:@"client"]; // 操纵系统
//    if ([DeviceDataInfo currentNetWork].hasValue) {
//        [header setObject:[DeviceDataInfo currentNetWork] forKey:@"network"]; // 网络
//    }
//    if ([DeviceDataInfo telephonyCarrier].hasValue) {
//        [header setObject:[DeviceDataInfo telephonyCarrier] forKey:@"operator"]; // 运营商
//    }
//
//    if ([DeviceDataInfo longitude].hasValue) {
//        [header setObject:[DeviceDataInfo longitude] forKey:@"longitude"]; // 经度
//    }
//
//    if ([DeviceDataInfo latitude].hasValue) {
//        [header setObject:[DeviceDataInfo latitude] forKey:@"latitude"];
//    }
    
    NSLog(@"url == %@, header == %@", api, header);
    
    for (NSString *key in header) {
        [request setValue:header[key] forHTTPHeaderField:key];
    }
    // 设置body
    [request setHTTPBody:body];
    return request;
}

+ (void)requestContent:(NSMutableURLRequest *)request success:(RequestSuccess)success failure:(RequestFailed)failure {
    
    [[_sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (!error) {
            bodyProcessResponseDataBlock(responseObject, success, failure);
        } else {
            if(failure) {
                NSLog(@"地址：%@ 错误：%@", [response URL], [error localizedDescription]);
//                [SVProgressHUD showErrorWithStatus:@"服务器开小差了,请稍后重试~!"];
                failure(@"服务器开小差了,请稍后重试~!");
            }
        }
    }] resume];
    
}

void(^bodyProcessResponseDataBlock)(id, RequestSuccess, RequestFailed) = ^(id data, RequestSuccess sucess, RequestFailed fail) {
    NSLog(@"获取的数据:%@",data);
    if (data == nil) {
        if (fail) fail(InVaildDataTipMsg);
        return;
    }
    
    NSInteger state = [data[@"status"] integerValue];
    
    switch (state) {
        case ResultCodeTypeSuccess: {
            if (sucess) sucess(data[@"data"]);
            return;
            break;
        }
        case ResultCodeTypeTokenFailure: {
            if (USER.isLogin) {
                [USER logout:^(id  _Nonnull success) {}];
            }
            break;
        }
        default: {
            if (fail) fail(data[@"message"]);
            return;
            break;
        }
    }
};

+ (void)uploadImageRequestWithAPI:(UploadImageType)uploadImageType imageKey:(NSString *)imageKey imageData:(NSData *)imageData success:(RequestSuccess)success failure:(RequestFailed)failure {
    NSString * str;
    switch (uploadImageType) {
        case UploadImageTypeOther:
            str = @"Other";
            break;
        case UploadImageTypeIdCard:
            str = @"IdCard";
            break;
        case UploadImageTypeUserAvatar:
            str = @"UserAvatar";
            break;
        case UploadImageTypeSalesReturn:
            str = @"SalesReturn";
            break;
        case UploadImageTypeBrandLogo:
            str = @"BrandLogo";
            break;
        case UploadImageTypeBanner:
            str = @"Banner";
            break;
        case UploadImageTypeProduct:
            str = @"Product";
            break;
        case UploadImageTypeCompanyLogo:
            str = @"CompanyLogo";
            break;
        case UploadImageTypeArticleCover:
            str = @"ArticleCover";
            break;
        case UploadImageTypeCategoryLogo:
            str = @"CategoryLogo";
            break;
        case UploadImageTypeArticleContent:
            str = @"ArticleContent";
            break;
        case UploadImageTypeCompanyLicense:
            str = @"CompanyLicense";
            break;
        case UploadImageTypeCommentMerchandise:
            str = @"CommentMerchandise";
            break;
        default:
            break;
    }
    NSString *api = [NSString stringWithFormat:@"%@%@%@", UploadAttachmentsPath, UploadImageAPI, str];
    AFHTTPSessionManager *httpRequestOperationManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:api]];
    httpRequestOperationManager.responseSerializer = [AFJSONResponseSerializer serializer];
    AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
    httpRequestOperationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/plain", nil];
    
    requestSerializer.timeoutInterval = kTimeOutTimeInterval *2;
    httpRequestOperationManager.requestSerializer = requestSerializer;
    
    NSMutableDictionary * header = [[NSMutableDictionary alloc] init];
    
//    if ([url containsString:StoreShareGetWxacodeAPI] || [url containsString:StoreShareGetWximageAPI]) {
//        [header setObject:@"application/x-www-form-urlencoded" forKey:@"Content-Type"];
//    } else {
    [header setObject:@"application/json;charset=UTF-8" forKey:@"Content-Type"];
//    }
    if (USER.userBaseInfo.token.hasValue) {
        [header setObject:USER.userBaseInfo.token forKey:@"token"];
    }
    NSString * psid = [DeviceInfoManager idfv];
    if (psid.hasValue) [header setObject:psid forKey:@"psid"];
    [header setObject:kChannelValue forKey:@"channel"];
    [header setObject:@"Extended" forKey:@"lifecycle"];
    
    [header setObject:APP.applicationVersion forKey:@"app-ver"];
    
    [header setObject:@"IOS" forKey:@"client"]; // 操纵系统
    
    NSLog(@"url == %@, header == %@", api, header);
    
    for (NSString *key in header) {
        [requestSerializer setValue:header[key] forHTTPHeaderField:key];
    }
    
    [SVProgressHUD showWithStatus:@"上传中..." maskType:SVProgressHUDMaskTypeNone];
    [httpRequestOperationManager POST:api parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:imageKey fileName:[NSString stringWithFormat:@"%@.jpg", imageKey] mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        bodyProcessResponseDataBlock(responseObject, success, failure);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure){
            failure([error localizedDescription]);
        }
    }];
}

@end
